const BaseRest = require('./rest.js');
const { think } = require('thinkjs');

module.exports = class extends BaseRest {
  /**
   * 创建一个用户
   */
  async postAction() {
    // 获取新用户信息
    const { account, password } = this.ctx.request.body.post;

    // 判断用户是否存在
    const model = this.model('user');
    const data = await model.where({ account }).find();
    const isEmpty = think.isEmpty(data);
    if (!isEmpty) {
      this.status = 409;
      return (this.body = {
        error: '用户已经存在',
        message: '请勿重复创建用户'
      });
    }

    // 创建新用户
    const passwordService = think.service('password');
    const id = await model.add({
      account,
      password: await passwordService.hash(password)
    });

    // 返回认证令牌
    const tokenService = think.service('token');
    const token = tokenService.sign({ id });
    this.body = { token };
  }
};
